package encryption;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.ArrayList;

import network.NetworkVars;

public class KeyRing {

	public ArrayList<PublicKey> keys = new ArrayList<PublicKey>();
	
	public KeyRing(String f){
		//goes into the file denoted by f, and then goes through it looking for key files.
		try {
			loadKeys(f);
		} catch (FileNotFoundException e) {
			System.err.println("Couldn't load keys from file: "+f);
			e.printStackTrace();
		}
	}
	
	public void addKey(PublicKey k){}
	//public boolean removeKey(PublicKey k){}
	
	public void saveRing(String f) throws FileNotFoundException{
			PrintWriter index = new PrintWriter(f);
			try {
				index.write(keys.size()+"\n");
				for(int i=0; i < keys.size(); i++){
					String file = NetworkVars.workingDir+File.separator+i+".key";
					index.write(file+"\n");
					FileOutputStream keyfile = new FileOutputStream(file);
					keyfile.write( keys.get(i).getEncoded() );//write out the key
					keyfile.flush();
					keyfile.close();
				}
				index.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
	}
	
	public void loadKeys(String f) throws FileNotFoundException{
		KeyReader k = new KeyReader();//create a key reader
		BufferedReader index = new BufferedReader(new FileReader(f));
		
		try {
			int num = Integer.parseInt(index.readLine());
			PublicKey[] tmp = new PublicKey[num];
			for(int i=0; i < tmp.length; i++){
				//go through the index file line by line and get the keys from the files named
				String file = index.readLine(); 
				tmp[i] = k.getPublicKey(file); 
			}
			index.close();

			for(PublicKey p : tmp){
				//if the public key isn't in our keyring, add it.
				if( !keys.contains(p) ){
					keys.add(p);
				}
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public boolean inKeyRing(PublicKey key){
		return keys.contains(key);
	}
}
